/*
*   @Author: 1296
*   @Date: 2025-03-18
*   @Description: 手势签到
*/

<template>
  <div>
    <div id="unlock-pattern">
      <canvas ref="canvas" width="300" height="300"></canvas>
    </div>
  </div>
</template>

<script>
import { ElMessage } from "element-plus";
import axios from "axios";
import store from "@/store";
import router from "@/router";
import { useRoute } from "vue-router";
import { onMounted } from "vue";

export default {
  name: 'DraftSign',
  setup() {
    const route = useRoute();
    onMounted(() => {
      const isVerify = route.query.isVerify;
      if (isVerify === '1' && sessionStorage.getItem(`${route.params.id}`) !== '1') {
        router.push({ path: `/verification/${isVerify}`, query: { section: route.params.id }});
      }
    });
  },
  data() {
    return {
      canvasContext: null,
      pointPositions: [],
      pattern: [],
      isMouseDown: false,
      linePath: [],
      api: axios.create({
        baseURL: store.getters.getBaseURL
      })
    };
  },
  mounted() {
      const canvas = this.$refs.canvas;
      this.canvasContext = canvas.getContext("2d");
      this.initPoints();
      this.drawPoints();

      // 绑定事件
      canvas.addEventListener("mousedown", this.startDrawing);
      canvas.addEventListener("mousemove", this.onDrawing);
      canvas.addEventListener("mouseup", this.endDrawing);
      canvas.addEventListener("mouseleave", this.endDrawing);
      canvas.addEventListener("touchstart", this.startDrawing);
      canvas.addEventListener("touchmove", this.onDrawing);
      canvas.addEventListener("touchend", this.endDrawing);

    // 添加拦截器
    this.api.interceptors.request.use(config => {
      const token = sessionStorage.getItem('userToken');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    this.api.interceptors.response.use(
        response => response,
        error => {
          if (error.response?.status === 401) {
            router.push('/loginAndRegister');
          }
          return Promise.reject(error);
        }
    );
  },
  methods: {
    initPoints() {
      this.pointPositions = [];
      const offset = 50;
      const gap = (300 - 2 * offset) / 2;
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          this.pointPositions.push({
            x: offset + col * gap,
            y: offset + row * gap,
            hit: false
          });
        }
      }
    },
    drawPoints() {
      this.clearCanvas();
      const ctx = this.canvasContext;

      // 绘制路径线条（蓝白渐变）
      if (this.linePath.length > 0) {
        const gradient = ctx.createLinearGradient(
            this.linePath[0].x, this.linePath[0].y,
            this.linePath[this.linePath.length-1].x, this.linePath[this.linePath.length-1].y
        );
        gradient.addColorStop(0, '#3b82f6');
        gradient.addColorStop(1, '#93c5fd');

        ctx.strokeStyle = gradient;
        ctx.lineWidth = 6;
        ctx.lineCap = 'round';
        ctx.shadowColor = 'rgba(59, 130, 246, 0.3)';
        ctx.shadowBlur = 8;
        ctx.beginPath();
        this.linePath.forEach((point, index) => {
          if (index === 0) ctx.moveTo(point.x, point.y);
          else ctx.lineTo(point.x, point.y);
        });
        ctx.stroke();
      }

      // 绘制9个点（蓝白风格）
      this.pointPositions.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 18, 0, Math.PI * 2);

        // 点样式
        if (point.hit) {
          const gradient = ctx.createRadialGradient(
              point.x, point.y, 0,
              point.x, point.y, 18
          );
          gradient.addColorStop(0, '#3b82f6');
          gradient.addColorStop(1, '#93c5fd');
          ctx.fillStyle = gradient;
          ctx.shadowColor = 'rgba(59, 130, 246, 0.5)';
        } else {
          ctx.fillStyle = '#ffffff';
          ctx.shadowColor = 'rgba(0, 0, 0, 0.1)';
        }

        // 公共样式
        ctx.shadowBlur = 12;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 2;
        ctx.strokeStyle = point.hit ? '#1e40af' : '#dbeafe';
        ctx.lineWidth = 2;

        ctx.fill();
        ctx.stroke();
      });
    },
    clearCanvas() {
      this.canvasContext.clearRect(0, 0, 300, 300);
    },
    getEventPos(e) {
      const rect = this.$refs.canvas.getBoundingClientRect();
      const clientX = e.touches ? e.touches[0].clientX : e.clientX;
      const clientY = e.touches ? e.touches[0].clientY : e.clientY;
      return {
        x: clientX - rect.left,
        y: clientY - rect.top
      };
    },
    checkAndAddPoint(pos) {
      for (let i = 0; i < this.pointPositions.length; i++) {
        const point = this.pointPositions[i];
        const distance = Math.sqrt(Math.pow(point.x - pos.x, 2) + Math.pow(point.y - pos.y, 2));
        if (distance < 20 && !point.hit) {
          point.hit = true;
          this.pattern.push(point);
          this.linePath.push({ x: point.x, y: point.y });
          this.drawPoints();
          break;
        }
      }
    },
    startDrawing(e) {
      e.preventDefault();
      this.resetPattern();
      this.isMouseDown = true;
      const pos = this.getEventPos(e);
      this.checkAndAddPoint(pos);
    },
    onDrawing(e) {
      if (!this.isMouseDown) return;
      e.preventDefault();
      const pos = this.getEventPos(e);
      this.drawPoints();
      const ctx = this.canvasContext;
      if (this.linePath.length > 0) {
        ctx.beginPath();
        ctx.moveTo(this.linePath[this.linePath.length - 1].x, this.linePath[this.linePath.length - 1].y);
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
      }
      this.checkAndAddPoint(pos);
    },
    endDrawing(e) {
      if (!this.isMouseDown) return;
      e.preventDefault();
      this.isMouseDown = false;
      this.drawPoints();

      if (this.pattern.length < 4) {
        ElMessage.error("请连接至少4个点");
      } else {
        // 按顺序返回点的索引
        const code = this.pattern.map(point =>
            this.pointPositions.indexOf(point) + 1
        );
        this.submitGestureSign(code);
      }
    },
    resetPattern() {
      this.pointPositions.forEach(point => point.hit = false);
      this.pattern = [];
      this.linePath = [];
    },
    submitGestureSign(gestureCode) {
      try {
        const aid = parseInt(this.$route.params.id); // 从路由参数中获取 aid
        this.api.put('/record/submit', {
          aid: aid,
          additionInfo: {
            gesture: gestureCode
          }
        }).then(response => {
          if (response.data.code === 200) {
            ElMessage.success("手势签到成功");
            // 跳转到个人页面
            const jobCode = sessionStorage.getItem('jobCode');
            setTimeout(() => {
              router.push(`/${jobCode}/personalPage`);
            }, 1000);
          } else {
            ElMessage.error("签到失败，请重试");
          }
        }).catch(error => {
          console.error('提交失败:', error);
          ElMessage.error("请求失败，请检查网络");
        });
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error("请求失败，请检查网络");
      }
    }
  }
};
</script>

<style scoped>
#unlock-pattern {
  width: 300px;
  height: 300px;
  margin: 50px auto;
  user-select: none;
  padding: 20px;
  background: linear-gradient(145deg, #f8fafc, #ffffff);
  border-radius: 25px;
  box-shadow: 0 15px 30px rgba(59, 130, 246, 0.1);
  transition: all 0.2s ease;
}

#unlock-pattern:active {
  transform: scale(0.98);
  box-shadow: 0 10px 20px rgba(59, 130, 246, 0.15);
}

canvas {
  width: 100% !important;
  height: 100% !important;
  border-radius: 18px;
  background: #f8fafc;
  box-shadow: inset 0 2px 8px rgba(59, 130, 246, 0.08);
  cursor: pointer;
  transition: box-shadow 0.2s;
}

canvas:hover {
  box-shadow: inset 0 2px 12px rgba(59, 130, 246, 0.12);
}

/* 移动端优化 */
@media (max-width: 480px) {
  #unlock-pattern {
    width: 280px;
    height: 280px;
    margin: 30px auto;
    padding: 15px;
  }
}
</style>